package com.kobeliu.mq;

import com.google.gson.Gson;
import com.kobeliu.api.mq.RabbitMQSMSConfig;
import com.kobeliu.pojo.mq.SMSContentQO;
import com.kobeliu.utils.SMSUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitMQSMSConsumer {

    @Autowired
    private SMSUtils smsUtils;

    //监听器 监听绑定的队列
    @RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
    public void watchQueue(String payLoad, Message message) throws Exception {

        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();

        if(receivedRoutingKey.equalsIgnoreCase(RabbitMQSMSConfig.ROUTING_KEY_SMS_SEND_LOGIN)){
            //此处为短信发送的消息消费处理
            SMSContentQO smsContentQO = new Gson().fromJson(payLoad, SMSContentQO.class);

            //此处为发送逻辑
            //smsUtils.sendTencentSMS(smsContentQO.getMobile(),smsContentQO.getContent());
            log.info("=======================================");
            log.info("得到的验证码为:{}",smsContentQO.getContent());
            log.info("=======================================");

        }

    }

    @RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
    public void watchQueue(Message message, Channel channel) throws Exception {

//        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();

//        String msg = message.getMessageProperties().getReceivedRoutingKey();
//
//        //message.getBody() 是一个byte数组
//        String msg1 = new String(message.getBody());

        try{
//            int a = 1/0;
            // 消息投递标签
            // 批量确认所有消费真获得的消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }catch (Exception e){
            e.printStackTrace();
            // 消息投递标签
            // 批量确认所有消费真获得的消息
            // requeue 重回队列的策略 true 重回 false丢弃
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
        }

    }
}
